//
//  SHAnchorPlayView.m
//  Netease
//
//  Created by 王方伟 on 2017/8/23.
//  Copyright © 2017年 wfw. All rights reserved.
//

#import "SHAnchorPlayView.h"
#import "NTESSessionMsgConverter.h"
#import "NSDictionary+Extension.h"
#import "NTESPreviewInnerView.h"
#import "NTESMicConnector.h"
#import "NTESMediaCapture.h"
#import "SHAnchorLiveView.h"
#import "NTESLiveManager.h"
#import "NTESDemoService.h"
#import "SHAlertAction.h"
#import "NTESLiveUtil.h"
#import "NTESUserUtil.h"


@interface SHAnchorPlayView ()<NTESPreviewInnerViewDelegate, NIMNetCallManagerDelegate, NTESAnchorLiveViewDelegate>
@property (strong, nonatomic) NTESPreviewInnerView *previewInnerView;
@property (assign, nonatomic) NIMVideoOrientation orientation;
@property (strong, nonatomic) NTESMediaCapture *capture;

@property (strong, nonatomic) NIMNetCallMeeting *preMeeting;
@property (strong, nonatomic) NIMNetCallMeeting *currentMeeting;

@property (strong, nonatomic) SHAnchorLiveView *liveView;

@property (strong, nonatomic) UIView *captureView;
@property (strong, nonatomic) UIView *requestToastView;

@property (assign, nonatomic) BOOL disableClick;
@property (copy, nonatomic) NSString *meetingname;
@property (assign, nonatomic) BOOL isDirect;
@end

@implementation SHAnchorPlayView


+ (instancetype)anchorPlayView{
    return [[SHAnchorPlayView alloc] init];
}

- (UIView *)captureView{
    if (_captureView == nil) {
        _captureView = [[UIView alloc] init];
        _captureView.clipsToBounds = YES;
    }
    return _captureView;
}

- (UIView *)previewInnerView{
    if (_previewInnerView == nil) {
        _previewInnerView = [NTESPreviewInnerView previewInnerView];
        _previewInnerView.delegate = self;
    }
    return _previewInnerView;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    _previewInnerView.frame = CGRectMake(0, 0, self.width, self.height);
    _previewInnerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    _captureView.frame = CGRectMake(0, 0, self.width, self.height);
    _captureView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    _liveView.frame = CGRectMake(0, 0, self.width, self.height);
    _liveView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doExitLive) name:@"DrageViewCloseNotification" object:nil];
        _capture = [[NTESMediaCapture alloc] init];
        _orientation = NIMVideoOrientationPortrait;
        [NTESLiveManager sharedLiveManager].orientation = NIMVideoOrientationPortrait;
        [[NIMAVChatSDK sharedSDK].netCallManager addDelegate:self];
        [self addSubview:self.captureView];
        [self setupCapture];
    }
    return self;
}


- (void)onLocalDisplayviewReady:(UIView *)displayView{
    [self.capture onLocalDisplayviewReady:displayView];
    if (self.previewInnerView) {
        [self bringSubviewToFront:self.previewInnerView];
    }
    
    // 默认美颜自然模式
    [[NIMAVChatSDK sharedSDK].netCallManager selectBeautifyType:NIMNetCallFilterTypeZiran];
    [self.previewInnerView updateBeautifyButton:YES];
}



#pragma mark 设置视频采集
- (void)setupCapture{
    NIMNetCallMediaType type = (NIMNetCallMediaType)[NTESLiveManager sharedLiveManager].type;
    __weak typeof(self) weakSelf = self;
    [weakSelf.previewInnerView switchToWaitingUI];
    [self.capture startPreview:type container:self.captureView handler:^(NSError *error) {
        [weakSelf addSubview:weakSelf.previewInnerView];
        if (error) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"直播失败，请检查网络和权限重新开启" preferredStyle:UIAlertControllerStyleActionSheet];
            SHAlertAction *action = [SHAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf onCloseLiving];
            }];
            [alertVC addAction:action];
            [DCURLRouter presentViewController:alertVC animated:YES completion:nil];
        }
    }];
}


- (void)onStartLiving{
    __weak typeof(self) weakSelf = self;
    [self requestVideoStreamWithCompletion:^(NSError *error) {
        if (error == nil) {
            if (!weakSelf.capture.isLiveStream) {
                [weakSelf.capture startLiveStreamHandler:^(NIMNetCallMeeting * _Nonnull meeting, NSError * _Nonnull error) {
                    if (error) {
                        weakSelf.disableClick = NO;
                        [SVProgressHUD showInfo:@"直播初始化失败"];
                        [weakSelf.previewInnerView switchToWaitingUI];
                    }else{
                        //将服务器连麦请求队列清空
                        [[NIMSDK sharedSDK].chatroomManager dropChatroomQueue:weakSelf.chatroom.roomId completion:nil];
                        //发一个全局断开连麦的通知给观众，表示之前的连麦都无效了
                        [weakSelf sendDisconnectedNotify:nil];
                        weakSelf.currentMeeting = meeting;
                        [SVProgressHUD dismiss];
                        weakSelf.disableClick = NO;
                        weakSelf.isDirect = YES;
                        dispatch_after(0, dispatch_get_main_queue(), ^{
                            weakSelf.liveView = [[SHAnchorLiveView alloc] initWithChatroom:weakSelf.chatroom currentMeeting:weakSelf.currentMeeting capture:weakSelf.capture delegate:weakSelf];
                            weakSelf.liveView.frame = CGRectMake(0, 0, weakSelf.width, weakSelf.height);
                            [weakSelf addSubview:weakSelf.liveView];
                        });
                    }
                }];
            }else{
                weakSelf.disableClick = NO;
            }
        }
    }];
}

- (void)onCloseLiveView{
    [self onCloseLiving];
}

- (void)sendDisconnectedNotify:(NTESMicConnector *)connector{
    NIMMessage *message = [NTESSessionMsgConverter msgWithDisconnectedMic:connector];
    NIMSession *session = [NIMSession session:self.chatroom.roomId type:NIMSessionTypeChatroom];
    [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
}

#pragma mark 关闭视频采集
- (void)onCloseLiving{
    if (_isDirect) {
        SHLog(@"直播中。。。");
    }else{
        if (self.disableClick) return;
        [self doExitLive];
        [self.superview removeFromSuperview];
        [DCURLRouter dismissViewControllerAnimated:YES completion:nil];
    }
    [DCURLRouter dismissViewControllerAnimated:YES completion:nil];

}

- (void)onCameraRotate{
    [self.capture switchCamera];
}

- (void)onRotate:(NIMVideoOrientation)orientation{
    if (orientation == NIMVideoOrientationPortrait) {
        _orientation = NIMVideoOrientationPortrait;
        [UIView animateWithDuration:0.5 animations:^{
            _previewInnerView.transform = CGAffineTransformIdentity;
            _previewInnerView.frame = CGRectMake(0, 0, self.width, self.height);
            [_previewInnerView layoutIfNeeded];
        }];
    }else{
        _orientation = NIMVideoOrientationLandscapeRight;
        [UIView animateWithDuration:0.5 animations:^{
            _previewInnerView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_2);
            _previewInnerView.frame = CGRectMake(0, 0, self.width, self.height);
            [_previewInnerView layoutIfNeeded];
            
        }];
    }
}

- (void)requestVideoStreamWithCompletion:(void(^)(NSError *error))completion{
    if (self.disableClick) {
        return;
    }
    _disableClick = YES;
    
    NSString *meetingName = [NSUUID UUID].UUIDString;
    self.meetingname = meetingName;
    [SVProgressHUD showMessage:@"加载中..."];
    _requestToastView  = [self getBeautifyToastView];
    
    if (_orientation == NIMVideoOrientationPortrait) {
        _requestToastView.transform = CGAffineTransformIdentity;
    }else{
        _requestToastView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_2);
    }
    [NTESLiveManager sharedLiveManager].requestOrientation = self.orientation;
    
    __weak typeof(self) weakSelf = self;
    [[NTESDemoService sharedService] requestLiveStream:meetingName completion:^(NSError *error, NIMChatroom *chatroom) {
        [SVProgressHUD dismiss];
        if (!error){
            NSInteger orientation = !(weakSelf.orientation ==NIMVideoOrientationLandscapeRight) ? 1 : 2;
            _chatroom = chatroom;
            NIMChatroomEnterRequest *request = [[NIMChatroomEnterRequest alloc] init];
            request.roomId = chatroom.roomId;
            request.roomNotifyExt = [@{
                                       NTESCMType:@([NTESLiveManager sharedLiveManager].type),
                                       NTESCMMeetingName:meetingName,
                                       NTESCMOrientation:@(orientation)
                                       } jsonBody];
            
            [[NIMSDK sharedSDK].chatroomManager enterChatroom:request completion:^(NSError *error, NIMChatroom *room, NIMChatroomMember *me) {
                if (!error) {
                    //这里拿到的是应用服务器的人数，没有把自己加进去，手动添加。
                    chatroom.onlineUserCount++;
                    //将room的扩展也加进去
                    chatroom.ext =[NTESLiveUtil jsonString:chatroom.ext addJsonString:request.roomNotifyExt];
                    [[NTESLiveManager sharedLiveManager] cacheMyInfo:me roomId:request.roomId];
                    [[NTESLiveManager sharedLiveManager] cacheChatroom:chatroom];
                    NIMNetCallMeeting *meeting = [[NIMNetCallMeeting alloc] init];
                    meeting.name = meetingName;
                    meeting.type = (NIMNetCallMediaType)[NTESLiveManager sharedLiveManager].type;
                    meeting.actor = YES;
                    weakSelf.preMeeting = meeting;
                    NIMNetCallOption *option = [NTESUserUtil fillNetCallOption:meeting];
                    option.bypassStreamingUrl = chatroom.broadcastUrl;
                    
                    [[NIMAVChatSDK sharedSDK].netCallManager reserveMeeting:meeting completion:^(NIMNetCallMeeting * _Nonnull currentMeeting, NSError * _Nonnull error) {
                        
                        [weakSelf.capture setMeeting:currentMeeting];
                        if (completion) {
                            completion(error);
                        }
                    }];
                }else{
                    if (completion) {
                        completion(error);
                    }
                }
            }];
        }else{
            if (completion) {
                completion(error);
            }
        }
    }];
}

- (UIView *)getBeautifyToastView{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    for ( UIView *view in [window subviews]) {
        if ([view isKindOfClass:[UIControl class]]) {
            for (UIView *toastView in view.subviews) {
                if ([toastView isKindOfClass:[SVProgressHUD class]]) {
                    return toastView;
                    break;
                }
            }
        }
    }
    return nil;
}

- (void)startAnchorPlay{

}

- (void)doExitLive{
    [[NIMAVChatSDK sharedSDK].netCallManager stopVideoCapture];
    
    if (self.chatroom) {
        [[NIMSDK sharedSDK].chatroomManager exitChatroom:self.chatroom.roomId completion:nil];
    }
    if (self.meetingname) {
        NIMNetCallMeeting *meeting = [[NIMNetCallMeeting alloc] init];
        meeting.name = self.meetingname;
        [[NIMAVChatSDK sharedSDK].netCallManager leaveMeeting:meeting];
    }
    
    [NTESLiveManager sharedLiveManager].type = NTESLiveTypeInvalid;
    NIMChatroomUpdateRequest *request = [[NIMChatroomUpdateRequest alloc] init];
    NSString *update = [@{NTESCMType  : @([NTESLiveManager sharedLiveManager].type),
                          NTESCMMeetingName: @""
                          } jsonBody];
    request.roomId = self.chatroom.roomId;
    request.updateInfo = @{@(NIMChatroomUpdateTagExt) : update};
    request.needNotify = YES;
    request.notifyExt  = update;
    [[NIMSDK sharedSDK].chatroomManager updateChatroomInfo:request completion:nil];
    [[NIMSDK sharedSDK].chatroomManager exitChatroom:self.chatroom.roomId completion:nil];
    [[NIMAVChatSDK sharedSDK].netCallManager leaveMeeting:self.currentMeeting];
    [[NTESLiveManager sharedLiveManager] removeAllConnectors];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
